package fancy.calendar.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import fancy.calendar.dataaccess.CalendarItemDataAccess;
import fancy.calendar.dataaccess.test.CalendarDataAccessTest;

@WebServlet("/CalendarServlet")
public class CalendarServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public CalendarServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String size = request.getParameter("c"); // Day, week, month ...
		response.getWriter().write(getSimulationJson()); // For testing
		
//		try {
//			 response.getWriter().write(getCalendarListJson(size));
//		} catch (SQLException | ClassNotFoundException e) {
//			response.getWriter().write("error");
//			e.printStackTrace();
//		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * For testing data
	 * 
	 * @return
	 */
	private String getSimulationJson() {
		Gson gson = new Gson();
		return gson.toJson(CalendarDataAccessTest.getSimulation());
	}

	/**
	 * For production
	 * 
	 * @param size
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	private String getCalendarListJson(String size) throws SQLException,
			IOException, ClassNotFoundException {
		Gson gson = new Gson();
		if (size == null) // For initial page, return calendar items of today
			return gson.toJson(CalendarItemDataAccess
					.getCalendarItemList(new Date()));

		switch (size) {
		case "today": // Return calendar items of today
			return gson.toJson(CalendarItemDataAccess
					.getCalendarItemList(new Date()));
		default: // Default, return null
			return null;

		}

	}
}
